package com.yyj.jan.user.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * Json工具，提供对象与json字符串之间的互转
 * @Classname: JsonUtil
 * @Description: 目前提供了jackson和gson方式 gson方式已弃用
 * @Author: kent(wangys@dreamtech.com.cn)
 * @Date: 2012-8-8 下午12:48:09
 * @Version:V6.0
 */
public class JsonUtil {
    // 定义jackson对象
    private static final ObjectMapper mapper = new ObjectMapper();
    /**
     * 将对象转换成json字符串
     * @param data
     * @return
     */
    public static String toJson(Object data) {
        try {
            String string = mapper.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json结果集转化为对象
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> T parseObject(String jsonData, Class<T> beanType) {
        try {
            T t = mapper.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json数据转换成list
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> List<T> parseArray(String jsonData, Class<T> beanType) {
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = mapper.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
